package web.java.z_JDBCUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtil {
	/**
	 * 数据库连接和关闭
	 * */
	private static String url="jdbc:mysql://localhost:3306/shop";
	private static String user="root";
	private static String password="root";
	//静态代码块记载数据库管理器类
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 数据库连接
	 * */
	public static Connection connection(){
		Connection conn=null;
		try{
			conn=DriverManager.getConnection(url, user, password);
			return conn;
		}catch(SQLException e){
			System.out.println("数据库连接出错！"+e.getMessage());
			throw new RuntimeException(e);
		}
	}
	/**
	 * 关闭数据库
	 * */
	public static void closeConn(Connection conn, Statement stmt){
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("关闭数据库管理器驱动出错！"+e.getMessage());
				throw new RuntimeException(e);
			}
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					System.out.println("关闭数据库出错！"+e.getMessage());
					throw new RuntimeException(e);
				}
			}
		}
	}
	public static void closeConn(Connection conn, Statement stmt, ResultSet result){
		if(result!=null){
			try {
				result.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("关闭结果集失败！"+e.getMessage());
				throw new RuntimeException(e);
			}
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					System.out.println("关闭数据库管理器驱动出错！"+e.getMessage());
					throw new RuntimeException(e);
				}
				if(conn!=null){
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						System.out.println("关闭数据库出错！"+e.getMessage());
						throw new RuntimeException(e);
					}
				}
			}
		}
	}
}
